import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) throws IOException {
        //创建服务器对象
        ServerSocket server = new ServerSocket(8888);
        System.out.println("服务器:" + server);
        //等待客户端连接
        Socket client = server.accept();
        System.out.println("客户端连接成功:" + client);
        //创建IO流
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();
        //服务器端接收客户端发送的对象
        while (true) {
            // 反转字符串  方法一
            byte[] b = new byte[1024];
            int length = is.read(b);
            if (length != -1) {
                String b1 = reverseString(new String(b, 0, length));
                System.out.println("反转客户端的消息:" + b1);
            }
            else {
                System.out.println("断开连接");
                break;
            }
            //服务器接收客户端的数据之后给客户端发送消息
            String string = "hello,client,我是server,已收到数据";
            byte[] sb = string.getBytes();
            os.write(sb);

        }
        //关闭资源
        os.close();
        is.close();
        server.close();
    }
    public static String reverseString(String s) {
        StringBuilder sb = new StringBuilder(s);
        return sb.reverse().toString();
    }

}







